<!-- eslint-disable vue/multi-word-component-names -->
<template>
    <!-- <el-row >
                <el-col :sapn="6">
                    <el-input v-model="id" placeholder="请输入id查询"></el-input>
                </el-col>
                <el-col :sapn="6">
                    <el-button type="primary">查询</el-button>
                    <el-button type="primary">重置</el-button>
                </el-col>
            </el-row>
            <el-table :data="tableData" style="width: 100%">
                <el-table-column prop="date" label="日期" width="180">
                </el-table-column>
                <el-table-column prop="name" label="姓名" width="180">
                </el-table-column>
                <el-table-column prop="address" label="地址">
                </el-table-column>
            </el-table> -->
    <!-- eslint-disable vue/multi-word-component-names -->
    <div>
        <div class="search">
            <el-form ref="form" :model="query" label-width="80px">
                <el-row>
                    <el-col :span="4">
                        <el-form-item label="客户姓名">
                            <el-input size="small" v-model="query.name"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="4">
                        <el-form-item label="客户手机">
                            <el-input size="small" v-model="query.phone"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="4">
                        <el-form-item label="归属人">
                            <el-input size="mini" v-model="query.owner"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="4">
                        <el-form-item label="渠道来源">
                            <el-select size="small" v-model="query.channelId" placeholder="请选择">
                                <el-option v-for="item in options" :key="item.value" :label="item.channelName"
                                    :value="item.channelId">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="4">
                        <el-form-item label="线索状态">
                            <el-select size="small" v-model="query.status" placeholder="请选择">
                                <el-option v-for="item in statusOption" :key="item.dictValue" :label="item.dictLabel"
                                    :value="item.dictValue">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="10">
                        <el-form-item label="跟进时间">
                            <el-date-picker v-model="value1" type="datetimerange" range-separator="至"
                                start-placeholder="开始日期" end-placeholder="结束日期">
                            </el-date-picker>
                        </el-form-item>
                    </el-col>
                    <el-col :span="5">
                        <el-form-item>
                            <el-button type="primary" size="small" @click="handleSearch">搜索</el-button>
                            <el-button size="small" @click="reset">重置</el-button>
                        </el-form-item>

                    </el-col>
                </el-row>
            </el-form>
            <div class="btn" style="display: flex;">
                <el-button type="primary" icon="el-icon-plus" size="small" @click="addShow" plain>添加</el-button>
                <el-button type="success" icon="el-icon-edit" size="small" plain  :disabled="delId.length !== 1" @click="editShow(null)">修改</el-button>
                <el-button type="danger" icon="el-icon-delete" size="small" plain :disabled="delId.length == 0"
                    @click="deleteClue(null)">删除</el-button>
                   <el-button type="warning" icon="el-icon-plus" size="small" @click="exportXlsx" plain>导出</el-button>
            </div>
        </div>
        <div class="table">
            <el-table :data="tableData" style="width: 100%" @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="55">
                </el-table-column>
                <el-table-column prop="clueId" label="线索编号" width="80">
                </el-table-column>
                <el-table-column prop="name" label="客户姓名" width="80">
                </el-table-column>
                <el-table-column prop="phone" label="手机号码">
                </el-table-column>
                <el-table-column prop="channelName" label="渠道来源">
                </el-table-column>
                <el-table-column prop="createTime" label="创建时间 " show-overflow-tooltip width="180">
                </el-table-column>
                <el-table-column prop="owner" label="线索归属">
                </el-table-column>
                <el-table-column prop="status" label="线索状态">
                    <template v-slot="scope">
                        <!-- scope.row 当前行的信息 -->
                        <!-- {{ scope.row }} -->
                        <el-tag v-if="scope.row.status == 1">已分配</el-tag>
                        <el-tag type="success" v-if="scope.row.status == 2">跟进中</el-tag>
                        <el-tag type="info" v-if="scope.row.status == 0">未知</el-tag>
                        <el-tag type="warning" v-if="scope.row.status == 4">伪线索</el-tag>
                        <el-tag type="danger" v-if="scope.row.status == 3">回收</el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="nextTime" label="下次跟进时间" width="180">
                </el-table-column>
                <el-table-column prop="address" label="操作" width="150">
                    <template v-slot="scope">
                        <el-button type="primary" size="mini" @click="editShow(scope.row.clueId)">修改</el-button>
                        <el-button type="danger" size="mini" @click="deleteClue(scope.row.clueId)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <page :total="total" :page="query.pageNum" @size="setSize" @current="setCurrent"></page>
        </div>
        <el-dialog title="title" :visible.sync="dialogVisible" width="50%">
            <div>
                <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
                    <el-row>
                        <el-col :span="12">
                            <el-form-item label="手机号码" prop="phone">
                                <el-input size="small" v-model="ruleForm.phone"></el-input>
                            </el-form-item>
                        </el-col>

                        <el-col :span="12">
                            <el-form-item label="客户姓名" prop="name">
                                <el-input size="small" v-model="ruleForm.name"></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="12">
                            <el-form-item label="渠道来源">
                                <el-select size="small" v-model="ruleForm.channelId" placeholder="请选择"
                                    @change="channelChange">
                                    <el-option v-for="item in options" :key="item.value" :label="item.channelName"
                                        :value="item.channelId">
                                    </el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>

                        <el-col :span="12">
                            <el-form-item label="活动信息">
                                <el-select size="small" v-model="ruleForm.activityId" placeholder="请选择">
                                    <el-option v-for="item in actOption" :key="item.value" :label="item.name"
                                        :value="item.activityId">
                                    </el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="12">
                            <el-form-item label="客户性别">
                                <el-radio-group v-model="ruleForm.gender">
                                    <el-radio v-for="(item, index) in sex" :key="index" :label="item.value">{{ item.label
                                        }}</el-radio>
                                </el-radio-group>
                            </el-form-item>
                        </el-col>

                        <el-col :span="12">
                            <el-form-item label="客户年龄">
                                <el-input-number size="small" v-model="ruleForm.age" :min="18" :max="100"
                                    label="描述文字"></el-input-number>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="12">
                            <el-form-item label="微信号">
                                <el-input size="small" v-model="ruleForm.weixin"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="QQ号码">
                                <el-input size="small" v-model="ruleForm.qq"></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitForm('ruleForm')">确定</el-button>
                <el-button @click="resetForm('ruleForm')">取消</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import page from './page.vue';
import { clueList, channels, clueStatus, activity, clueAdd, clueDel, summary, clueEdit, exportClue} from '@/api/clue';
export default {
    components: {
        page
    },
    data() {
        var validatePhone = (rule,value,callback) => {
            const reg = /^1[3-9]\d{9}$/;
            if(value){
                if(reg.test(value)){
                    callback()
                }else{
                callback(new Error("请输入十一位手机号"))
            }
        }else{
              callback(new Error("手机号不能为空"))
        }
    };
        return {
            dialogVisible: false,
            id: null,
            title:null,
            tableData: [],
            options: [],
            statusOption: [],
            actOption: [],
            // value: '',
            value1: '',
            query: {
                pageNum: 1,
                pageSize: 10,
                name: null,
                channelId: null,
                status: null,
                phone: null,
                owner: null
            },
            total: 0,
            delId: [],
            sex: [
                {
                    label: "男",
                    value: 0
                }, {
                    label: "女",
                    value: 1
                }, {
                    label: "未知",
                    value: 2
                }
            ],
            ruleForm: {
                phone: '',
                name: '',
                gender: 0,
                activityId: null,
                channelId: null,
                age: null,
                weixin: "",
                qq: ""
            },
            rules: {
                name: [
                    { required: true, message: '请输入活动名称', trigger: 'blur' },
                ],
                phone: [
                    { required: true, validator:validatePhone, trigger: 'blur' },


                ]
            }
        }
    },
    created() {
        this.getList()
        this.getChannels()
        this.getStatus()
    },
    methods: {
        // 修改打开弹窗
        editShow(val){
            // 从表格当前行修改
            if(val){
                this.delId[0]= val
            }
            this.dialogVisible = true
            this.title = "修改"
            summary(this.delId).then( async(res) => {
                this.ruleForm.name = res.data.name
                this.ruleForm.gender = res.data.gender
                this.ruleForm.phone = res.data.phone
                this.ruleForm.qq = res.data.qq
                this.ruleForm.weixin = res.data.weixin
                this.ruleForm.age = res.data.age
                if(res.data.channelId){
                    this.ruleForm.channelId = res.data.channelId
                    //再次调用活动列表
                    
                    await this.channelChange(res.data.channelId)
                    this.ruleForm.activityId = res.data.activityId
                }
            })
        },
        // 删除
        deleteClue(index) {
            let id = index ? index : this.delId

            this.$confirm(`此操作将永久删除编号为${id}得数据, 是否继续?`, '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                clueDel(this.delId).then(res => {
                    this.getList()
                     this.$message({
                    type: 'success',
                    message: '删除成功!'
                });
                })
                .catch(err => {
                this.$message({
                    type: 'error',
                    message: err.msg
                });
            })
               
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            });
        },
        //渠道来源发生变化时触发
        channelChange(val) {
            this.ruleForm.activityId = null
            activity(val).then(res => {
                this.actOption = res.data
            })
        },

        submitForm(formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    if(this.title == "新增"){
                        //添加接口
                    clueAdd(this.ruleForm).then(res => {
                        // 新增成功后
                        console.log(res)
                        if (res.code == 200) {
                            this.$message({
                                message: "新增成功",
                                type: "success"
                            })
                            // 关闭模态框
                            this.dialogVisible = false
                            //列表刷新
                            this.getList()
                            // 重置表单信息校验
                            this.$refs[formName].resetFields();
                        }
                    })
                        .catch(err => {
                            this.$message({
                                message: err.msg,
                                type: "error"
                            })
                        })
                    }else{
                        // 参数
                        let data = {
                            clueId:this.delId[0],
                            ...this.ruleForm
                        }
                        //修改
                        clueEdit(data).then(res =>{
                            this.$message.success("修改成功")
                            this.dialogVisible = false
                            this.getList()
                        })
                    }
                    
                } else {
                    console.log('error submit!!');
                    return false;
                }
            });
        },
        resetForm(formName) {
            this.$refs[formName].resetFields();
            this.dialogVisible = false
            // 手动清除
            this.ruleForm.channelId = null
            this.ruleForm.activityId = null
        },

        // 点击新增
        addShow() {
            this.dialogVisible = true
            this.title = "新增"
            this.$nextTick(() => {
                // 重置表单信息及校验
                this.$refs.ruleForm.resetFields();
            })

        },
        // 重置
        reset() {
            this.query.pageNum = 1
            this.query.pageSize = 10
            this.query.name = null
            this.query.channelId = null
            this.query.phone = null
            this.query.owner = null
            this.getList()

        },
        // 查询
        handleSearch() {
            // 重置页码 从一开始
            this.query.pageNum = 1
            this.getList()
        },
        // 线索状态
        async getStatus() {
            const res = await clueStatus()
            console.log(res, "========")
            this.statusOption = res.data
        },
        // 线索列表
        getChannels() {
            channels().then(res => {
                this.options = res.data
            })
        },
        setSize(val) {
            this.query.pageSize = val
            this.query.pageNum = 1
            this.getList()
        },
        setCurrent(val) {
            this.query.pageNum = val
            // 重新调用接口
            this.getList()
        },
        getList() {
            clueList(this.query).then(res => {
                this.tableData = res.rows
                this.total = res.total
            })

        },
        // 多选
        handleSelectionChange(val) {
            this.delId = []
            for (const item of val) {
                this.delId.push(item.clueId)
            }
        },
        handleSizeChange(val) {
            this.query.pageSize = val
            this.query.pageNum = 1
            this.getList()
        },
        handleCurrentChange(val) {
            this.query.pageNum = val
            // 重新调用接口
            this.getList()
        },
        exportXlsx(){
            exportClue(this.query).then(res => {
                console.log(res)
                // 创建一个blob对象，存储excel文件数据
                let blob = new Blob([res])
                const link = document.createElement("a")
                // 创建一个下载链接，并将其赋值给href
                link.href = window.URL.createObjectURL(blob)
                link.target = "_blank"
                // 设置文件名
                let nowTime = new Date()
                link.setAttribute('download',`导出课程${nowTime.getTime()}.xlsx`)
                // 将a标签1添加到页面上
                document.body.appendChild(link)
                // 触发点击事件
                link.click()
                // 移除a标签
                document.body.removeChild(link)
            })
            .catch(err => {
                console.log(err)
            })
        }
    },
}
</script>



<style lang="scss" scoped></style>
